from flask import Blueprint, request, render_template, redirect, url_for
from utils import response
from services.product_service import ProductService
from config import Config  # 导入配置

# 创建蓝图
admin_product_bp = Blueprint('admin_product', __name__)

@admin_product_bp.route('/list', methods=['GET'])
@admin_product_bp.route('/list/<int:page>')
def list(page=1):
    # 使用Config中的PAGE_SIZE
    data = ProductService.list(page, pagesize=Config.PAGE_SIZE)
    return render_template('product/list.html', data=data)
    # return response(200, '产品信息获取成功', data)

@admin_product_bp.route('/add', methods=['POST'])
def add():
    name = request.form.get('name')
    desc = request.form.get('desc')
    category = request.form.get('category')  # 新添加的字段
    quality = request.form.get('quality')  # 新添加的字段
    specification = request.form.get('specification')  # 新添加的字段

    # 验证必要字段
    if not name or not desc or not category or not quality or not specification:
        return response(400, '请填写所有必要字段')

    # 检查文件上传
    if 'file' not in request.files:
        return response(400, '请选择产品图片')

    file = request.files['file']

    # 添加产品记录
    try:
        ProductService.add(
            name,
            desc,
            category,  # 新添加的字段
            quality,  # 新添加的字段
            specification,  # 新添加的字段
            file
        )
        return response(200, '产品添加成功')
    except Exception as e:
        return response(500, f'添加失败: {str(e)}')

@admin_product_bp.route('/delete/<id>', methods=['DELETE'])
def delete(id):
    result = ProductService.delete_by_id(id)
    if result:
        return response(200, '删除成功')
    else:
        return response(404, '删除失败，未找到对应ID的产品')

@admin_product_bp.route('/update/<id>', methods=['PUT'])
def update(id):
    name = request.form.get('name')
    desc = request.form.get('desc')
    comment = request.form.get('comment')
    file = request.files.get('file')

    # 验证必要字段
    if not name or not desc or not comment:
        return response(400, '请填写所有必要字段')

    try:
        # 调用更新服务
        ProductService.update(id, name, desc, comment, file)
        return response(200, '产品信息更新成功')
    except Exception as e:
        return response(500, f'更新失败: {str(e)}')